package com.hebtu.helper.modules.oss.config;

import com.hebtu.helper.common.exception.HelperException;
import com.hebtu.helper.common.utils.DateUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author YKF
 * @date 2019/6/17 10:07
 */
public class OssUtile {

    private OssConfig config;
    private COSCredentials credentials;
    private ClientConfig clientConfig;

    /**
     * 初始化配置
     */
    public OssUtile(){
        config=new OssConfig("help-1255334830.file.myqcloud.com",null,1255334830,"AKIDTpzyoXw2c3IMJ6pdeLuKaP8g3EHBHTq1"
                ,"IOabTEoDRUM2Yw9Azd6NVL0Uu9D6nMkw","help","ap-beijing");
        init();
    }

    private void init(){
        //1、初始化用户身份信息(secretId, secretKey)
        credentials = new BasicCOSCredentials(config.getQcloudSecretId(), config.getQcloudSecretKey());

        //2、设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        clientConfig = new ClientConfig(new Region(config.getQcloudRegion()));
    }


    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }


    public String upload(InputStream inputStream, String path) {
        try {
            COSClient client = new COSClient(credentials, clientConfig);

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());
            String bucketName = config.getQcloudBucketName() +"-"+ config.getQcloudAppId();
            PutObjectRequest request = new PutObjectRequest(bucketName, path, inputStream, metadata);
            PutObjectResult result = client.putObject(request);

            client.shutdown();
            if(result.getETag() == null){
                throw new HelperException("上传文件失败，请检查配置信息");
            }
        } catch (IOException e) {
            throw new HelperException("上传文件失败，请检查配置信息", e);
        }

        return config.getQcloudDomain() + "/" + path;
    }


    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getQcloudPrefix(), suffix));
    }


    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getQcloudPrefix(), suffix));
    }

    /**
     * 文件路径
     * @param prefix 前缀
     * @param suffix 后缀
     * @return 返回上传路径
     */
    public String getPath(String prefix, String suffix) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + uuid;

        if(StringUtils.isNotBlank(prefix)){
            path = prefix + "/" + path;
        }

        return path + "." + suffix;
    }
}
